<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>月度數據記錄與統計工具 (雲端版)</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .nav-btn-active { background-color: #4f46e5; color: white; }
        .nav-btn-inactive { background-color: #e5e7eb; color: #374151; }
        .hidden { display: none; }
    </style>
</head>
<body class="bg-gray-100">

    <!-- 登入註冊視圖 -->
    <div id="auth-view" class="flex items-center justify-center min-h-screen">
        <div class="w-full max-w-md bg-white rounded-xl shadow-lg p-8">
            <h2 class="text-2xl font-bold text-center text-gray-800 mb-6">使用者登入或註冊</h2>
            <form id="login-form" class="space-y-4">
                <div>
                    <label for="username" class="block text-sm font-medium text-gray-700">帳號</label>
                    <input type="text" id="username" required autocomplete="username" class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                </div>
                <div>
                    <label for="password" class="block text-sm font-medium text-gray-700">密碼</label>
                    <input type="password" id="password" required autocomplete="current-password" class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                </div>
                <div id="auth-error" class="text-red-500 text-sm text-center h-4"></div>
                <div class="flex space-x-4 pt-2">
                    <button type="button" id="login-btn" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700">登入</button>
                    <button type="button" id="signup-btn" class="w-full flex justify-center py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">註冊</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 主應用程式視圖 -->
    <div id="app-view" class="hidden w-full max-w-5xl mx-auto my-8">
        <div class="bg-white rounded-xl shadow-lg p-6 sm:p-8">
            <header class="mb-6">
                <div class="flex justify-between items-center">
                    <h1 id="main-title" class="text-2xl sm:text-3xl font-bold text-gray-800">當月數據記錄</h1>
                    <div class="text-right">
                         <p id="user-display" class="text-sm text-gray-600">目前使用者: <span class="font-semibold"></span></p>
                         <button id="logout-btn" class="text-sm text-indigo-600 hover:text-indigo-800 font-semibold">退出登入</button>
                    </div>
                </div>
            </header>
            
            <nav class="flex justify-center space-x-4 mb-8">
                <button id="view-current-btn" class="px-5 py-2 rounded-md font-semibold transition-colors duration-200">當月數據</button>
                <button id="view-history-btn" class="px-5 py-2 rounded-md font-semibold transition-colors duration-200">查看歷史</button>
            </nav>

            <div class="bg-gray-50 p-6 rounded-lg mb-8 border border-gray-200">
                <form id="itemForm" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-6 items-end">
                    <!-- 表單輸入項 -->
                    <div class="form-group"><label for="model" class="block text-sm font-medium text-gray-700 mb-1">型號</label><input type="text" id="model" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"></div>
                    <div class="form-group"><label for="quantity" class="block text-sm font-medium text-gray-700 mb-1">數量</label><input type="number" id="quantity" min="0" step="1" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"></div>
                    <div class="form-group"><label for="price" class="block text-sm font-medium text-gray-700 mb-1">價格</label><input type="number" id="price" min="0" step="0.01" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"></div>
                    <div class="form-group"><label for="date" class="block text-sm font-medium text-gray-700 mb-1">時期</label><input type="date" id="date" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"></div>
                    <div class="form-group sm:col-span-2 lg:col-span-1"><button type="submit" class="w-full bg-indigo-600 text-white font-semibold py-2 px-4 rounded-md shadow-sm hover:bg-indigo-700">新增記錄</button></div>
                </form>
            </div>

            <div id="monthly-records-container" class="space-y-12"></div>
        </div>
    </div>
    
    <script>
        // 定義一個初始化函數，確保所有程式碼在SDK載入後執行
        function initializeApp() {
            // ===================================================================================
            // !!! 重要: 請將下面的 App ID, App Key 和 serverURLs 替換成你自己的 LeanCloud 應用程式憑證 !!!
            // ===================================================================================
            const APP_ID = 'E20WnUeofp51HtiwKGpd68fM-gzGzoHsz';
            const APP_KEY = 'WA19bdiYl96N5wpL02Ugdb23';
            const SERVER_URLS = 'https://e20wnueo.lc-cn-n1-shared.com';

            // 初始化 LeanCloud SDK
            AV.init({
                appId: APP_ID,
                appKey: APP_KEY,
                serverURLs: SERVER_URLS 
            });

            // --- 全域狀態 ---
            let currentUser = AV.User.current();
            let currentPage = 'current';

            // --- UI 元素取得 ---
            const authView = document.getElementById('auth-view');
            const appView = document.getElementById('app-view');
            const userDisplay = document.querySelector('#user-display span');
            const authError = document.getElementById('auth-error');
            const loginForm = document.getElementById('login-form');
            const itemForm = document.getElementById('itemForm');
            const dateInput = document.getElementById('date');
            const monthlyContainer = document.getElementById('monthly-records-container');
            const viewCurrentBtn = document.getElementById('view-current-btn');
            const viewHistoryBtn = document.getElementById('view-history-btn');
            const mainTitle = document.getElementById('main-title');
            const logoutBtn = document.getElementById('logout-btn');


            // --- 認證和狀態管理 ---

            function checkLoginStatus() {
                currentUser = AV.User.current(); // 每次檢查都重新取得目前使用者
                if (currentUser) {
                    userDisplay.textContent = currentUser.get('username');
                    authView.classList.add('hidden');
                    appView.classList.remove('hidden');
                    setDefaultDate();
                    refreshDisplay();
                } else {
                    authView.classList.remove('hidden');
                    appView.classList.add('hidden');
                }
            }

            // 登入
            document.getElementById('login-btn').addEventListener('click', async () => {
                authError.textContent = '';
                const username = document.getElementById('username').value.trim();
                const password = document.getElementById('password').value;
                try {
                    await AV.User.logIn(username, password);
                    checkLoginStatus();
                } catch (error) {
                    authError.textContent = `登入失敗: ${error.message}`;
                }
            });

            // 註冊
            document.getElementById('signup-btn').addEventListener('click', async () => {
                authError.textContent = '';
                const username = document.getElementById('username').value.trim();
                const password = document.getElementById('password').value;
                const newUser = new AV.User();
                newUser.setUsername(username);
                newUser.setPassword(password);
                try {
                    await newUser.signUp();
                    authError.textContent = '註冊成功！請直接登入。';
                    loginForm.reset();
                } catch (error) {
                    authError.textContent = `註冊失敗: ${error.message}`;
                }
            });

            // 登出
            logoutBtn.addEventListener('click', () => {
                AV.User.logOut();
                checkLoginStatus();
            });


            // --- 資料操作函數 (LeanCloud) ---
            
            async function getItemsFromCloud() {
                if (!currentUser) return [];
                const query = new AV.Query('Items');
                query.equalTo('owner', currentUser); // 只查詢屬於目前使用者的記錄
                query.descending('createdAt'); // 按建立時間排序
                try {
                    const items = await query.find();
                    // 將 LeanCloud 物件轉換為普通 JS 物件
                    return items.map(item => ({ id: item.id, ...item.attributes }));
                } catch (error) {
                    console.error("取得資料失敗:", error);
                    alert(`取得資料失敗: ${error.message}`);
                    return [];
                }
            }

            const groupItemsByMonth = (items) => {
                return items.reduce((acc, item) => {
                    const monthKey = item.date.substring(0, 7);
                    if (!acc[monthKey]) acc[monthKey] = [];
                    acc[monthKey].push(item);
                    return acc;
                }, {});
            };
            
            const renderMonthlyGroups = (groupedItems) => {
                monthlyContainer.innerHTML = '';
                const sortedMonths = Object.keys(groupedItems).sort().reverse();

                if (sortedMonths.length === 0) {
                    monthlyContainer.innerHTML = '<p class="text-center text-gray-500 py-8">目前視圖下無記錄。</p>';
                    return;
                }

                sortedMonths.forEach(monthKey => {
                    const items = groupedItems[monthKey];
                    items.sort((a, b) => new Date(b.date) - new Date(a.date));
                    const [year, month] = monthKey.split('-');
                    const monthTitle = `${year}年 ${parseInt(month, 10)}月`;
                    const totalQuantity = items.reduce((sum, item) => sum + Number(item.quantity), 0);
                    const totalPrice = items.reduce((sum, item) => sum + (Number(item.quantity) * Number(item.price)), 0);

                    const monthGroupEl = document.createElement('div');
                    monthGroupEl.className = 'month-group';
                    monthGroupEl.innerHTML = `
                        <h2 class="text-xl font-bold text-gray-800 mb-4 pb-2 border-b border-gray-200">${monthTitle}</h2>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-6 text-center">
                            <div class="bg-blue-50 p-4 rounded-lg border border-blue-200"><h3 class="text-blue-800 font-medium text-sm">總數量</h3><p class="text-2xl font-bold text-blue-900 mt-1">${totalQuantity}</p></div>
                            <div class="bg-green-50 p-4 rounded-lg border border-green-200"><h3 class="text-green-800 font-medium text-sm">總價格 (元)</h3><p class="text-2xl font-bold text-green-900 mt-1">${totalPrice.toLocaleString('zh-TW', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</p></div>
                        </div>
                        <div class="overflow-x-auto bg-white rounded-lg shadow-sm border border-gray-200">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50"><tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">型號</th> <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">數量</th> <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">價格</th> <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">時期</th> <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr></thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    ${items.map(item => `
                                        <tr class="hover:bg-gray-50">
                                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${item.model}</td> <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">${item.quantity}</td> <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">${parseFloat(item.price).toFixed(2)}</td> <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">${item.date}</td>
                                            <td class="px-6 py-4 whitespace-nowrap text-center text-sm font-medium"><button data-id="${item.id}" class="text-red-600 hover:text-red-900 delete-btn">刪除</button></td>
                                        </tr>
                                    `).join('')}
                                </tbody>
                            </table>
                        </div>
                    `;
                    monthlyContainer.appendChild(monthGroupEl);
                });
            }
            
            async function refreshDisplay() {
                const allItems = await getItemsFromCloud();
                const today = new Date();
                const currentMonthKey = today.toISOString().substring(0, 7);

                if (currentPage === 'current') {
                    mainTitle.textContent = '當月數據記錄';
                    viewCurrentBtn.className = 'px-5 py-2 rounded-md font-semibold nav-btn-active';
                    viewHistoryBtn.className = 'px-5 py-2 rounded-md font-semibold nav-btn-inactive';
                    const currentMonthItems = allItems.filter(item => item.date.substring(0, 7) === currentMonthKey);
                    renderMonthlyGroups(groupItemsByMonth(currentMonthItems));
                } else {
                    mainTitle.textContent = '歷史數據記錄';
                    viewHistoryBtn.className = 'px-5 py-2 rounded-md font-semibold nav-btn-active';
                    viewCurrentBtn.className = 'px-5 py-2 rounded-md font-semibold nav-btn-inactive';
                    const historyItems = allItems.filter(item => item.date.substring(0, 7) !== currentMonthKey);
                    renderMonthlyGroups(groupItemsByMonth(historyItems));
                }
            }

            const setDefaultDate = () => dateInput.value = new Date().toISOString().split('T')[0];

            // --- 應用程式事件監聽 ---
            itemForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                const Item = AV.Object.extend('Items');
                const item = new Item();
                item.set('model', document.getElementById('model').value.trim());
                item.set('quantity', Number(document.getElementById('quantity').value));
                item.set('price', Number(document.getElementById('price').value));
                item.set('date', dateInput.value);
                item.set('owner', AV.User.current()); // 關鍵：將記錄與目前使用者關聯

                // 設定ACL，保證只有建立者能讀寫
                const acl = new AV.ACL();
                acl.setReadAccess(AV.User.current(), true);
                acl.setWriteAccess(AV.User.current(), true);
                item.setACL(acl);

                try {
                    await item.save();
                    refreshDisplay();
                    itemForm.reset();
                    setDefaultDate();
                } catch (error) {
                    alert(`儲存失敗: ${error.message}`);
                }
            });

            monthlyContainer.addEventListener('click', async (e) => {
                if (e.target.classList.contains('delete-btn')) {
                    const idToDelete = e.target.dataset.id;
                    if (confirm('您確定要刪除這條記錄嗎？')) {
                        const item = AV.Object.createWithoutData('Items', idToDelete);
                        try {
                            await item.destroy();
                            refreshDisplay();
                        } catch (error) {
                            alert(`刪除失敗: ${error.message}`);
                        }
                    }
                }
            });

            viewCurrentBtn.addEventListener('click', () => { currentPage = 'current'; refreshDisplay(); });
            viewHistoryBtn.addEventListener('click', () => { currentPage = 'history'; refreshDisplay(); });

            // --- 初始化 ---
            checkLoginStatus();
        }
    </script>
    <!-- 修正：更換為另一個全球通用的穩定 CDN (jsdelivr)，並使用 onload 屬性來觸發初始化函數 -->
    <script src="https://cdn.jsdelivr.net/npm/leancloud-storage/dist/av.min.js" onload="initializeApp()"></script>
</body>
</html>
